package com.fingard.dsp.bank.directbank.chinapay05;

import chinapay.util.SecureUtil;
import com.chinapay.secss.SecssConstants;
import com.chinapay.secss.SecssUtil;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.chinapay01.util.SDKUtil;
import com.fingard.dsp.bank.directbank.chinapay05.util.DigestMD5;
import com.fingard.dsp.bank.directbank.chinapay05.util.MsgUtil;
import com.fingard.dsp.bank.directbank.citic04.util.yldfdemo;
import com.fingard.dsp.bank.helpers.YBTHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.NameValuePair;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.*;

import static com.fingard.dsp.bank.helpers.YBTHelper.getBatSeqNo;

public class ChinaPay05BatPayRec extends ChinaPay05Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1988.ownAct, "batpay");
            if (actItem == null) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req1988.ownAct + "]商户配置信息!";
                return retAts;
            }

            StringBuilder sbFileContent = new StringBuilder();

            String tmpPayDate = Format.Date8Format.format(p_req1988.getPayDateTime());
            String tmpBatSeqNo = YBTHelper.getBatSeqNo(getTempFileDirectory(p_req1988.getPayDateTime()), 6);
            String tmpUploadFileName = actItem.merchantId + "_" + tmpPayDate + "_" + tmpBatSeqNo + ".txt";
            String tmpLocalMarkPath = getTempFileDirectory(p_req1988.getPayDateTime()) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次代付请求文件保存本机路径: " + tmpLocalMarkPath);
            String totalNum = p_req1988.totalNum;
            String totalAmt = p_req1988.totalAmt;

            String tmpReqHeader = MessageFormat.format("{0}|{1}|{2}|{3}", actItem.merchantId, tmpBatSeqNo, totalNum, amountMultiply100(totalAmt));
            sbFileContent.append(tmpReqHeader).append("\r\n");
            while (p_req1988.readRecord()) {
                StringBuilder tmpReqBodyDetail = new StringBuilder();
                tmpReqBodyDetail.append(tmpPayDate).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.askNumber).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.recAct).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.recName).append("|");
                String bankCode = getBankConfig().getMapValueByKey("bankCodeMapping", p_req1988.readedDetail.recBankCode);
                tmpReqBodyDetail.append(StringHelper.hasAnyChar(bankCode) ? bankCode : p_req1988.readedDetail.recBankName).append("|");
                String[] reArea = p_req1988.readedDetail.recAreaName.split("_");
                tmpReqBodyDetail.append(reArea[0]).append("|");
                tmpReqBodyDetail.append(reArea[1]).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.recBankLocation).append("|");
                tmpReqBodyDetail.append(amountMultiply100(p_req1988.readedDetail.payAmount)).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.purpose).append("|");
                tmpReqBodyDetail.append(p_req1988.readedDetail.isPrivate.equals("1") ? "00" : "01");

                sbFileContent.append(tmpReqBodyDetail).append("\r\n");
            }


            String chkValue1 = SecureUtil.digitalSign(actItem.merchantId, sbFileContent.toString(), actItem.ownKeyStorePath);
            WriteBankLogLn2("批量代付文件上传chkValue:\r\n" + chkValue1);
            String plain = sbFileContent.toString() + chkValue1;
            WriteBankLogLn2("待上传批量代付请求文件内容:\r\n" + plain);
            FileHelper.writeFile(tmpLocalMarkPath, plain, getCharset("GBK", "batpay"));
            // 批次流水映射存入本地
            WriteBankLogLn2("批次流水映射文件内容:\r\n" + tmpBatSeqNo);
            String tmpBatSeqNoFilePath = getDataFileDirectory(p_req1988.getPayDateTime()) + File.separator + p_req1988.reqBatchNO + ".txt";
            WriteBankLogLn2("本地批次流水映射文件路径:" + tmpBatSeqNoFilePath);
            FileHelper.writeFile(tmpBatSeqNoFilePath, tmpBatSeqNo, getCharset("GBK", "batpay"));
            //待上传文件名
            byte[] temSen = MsgUtil.getBytes(new File(tmpLocalMarkPath));
            String tian = new String(temSen, getCharset("GBK", "batpay"));
            String chkValue2 = DigestMD5.MD5Sign(actItem.merchantId, tmpUploadFileName, plain.getBytes(getCharset("GBK", "batpay")), actItem.ownKeyStorePath);

            NameValuePair[] param = {
                    new NameValuePair("merId", actItem.merchantId),
                    new NameValuePair("fileName", tmpUploadFileName),
                    new NameValuePair("fileContent", tian),
                    new NameValuePair("chkValue", chkValue2)
            };
            String reqStr = "merId=" + actItem.merchantId + "&fileName=" + tmpUploadFileName + "&fileContent=" + tian + "&chkValue=" + chkValue2;
            WriteBankLogStep2(reqStr);
            String result = sendBatch(param, bankFront.getUrl("batch"), "batpay");
            if (result != null) {
                Map<String, String> resultMap = convertToMap(result);
                String responseCode = resultMap.get("responseCode");
                if (StringHelper.hasAnyChar(responseCode)) {
                    retAts.respCode = "0";
                    retAts.respInfo = resultMap.get("message");
                    retAts.transState = responseCode;
                    retAts.payInfoCode = responseCode;
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = resultMap.get("message");
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "银行响应为空！";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req1998.ownAct, "batpay");
            if (actItem == null) {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req1998.ownAct + "]商户配置信息!";
            }
            String tmpPaySendDate = Format.Date8Format.format(p_req1998.getBgnDateTime());
            String tmpBatSeqNoPath = getDataFileDirectory(p_req1998.getBgnDateTime()) + File.separator + p_req1998.reqBatchNO + ".txt";
            WriteBankLogLn2("本地批次流水映射文件路径:" + tmpBatSeqNoPath);
            File tmpBatSeqNoFile = new File(tmpBatSeqNoPath);
            if (!tmpBatSeqNoFile.exists()) {
                retAts.respCode = "-1";
                retAts.respInfo = "批次流水映射文件[" + tmpBatSeqNoPath + "]不存在!";
                retAts.writeAfterDetail();
                return retAts;
            }
            String tmpSeqNoContent = FileHelper.readFileText(tmpBatSeqNoPath, getCharset("GBK", "batpay"));
            WriteBankLogLn2("本地批次流水映射文件内容:" + tmpSeqNoContent);
            if (StringHelper.isNullOrEmpty(tmpSeqNoContent)) {
                retAts.respCode = "-1";
                retAts.respInfo = "批次流水映射文件内容为空!";
                retAts.writeAfterDetail();
                return retAts;
            }
            String orFileName = actItem.merchantId + "_" + tmpPaySendDate + "_" + tmpSeqNoContent + ".txt";
            String tmpPalin = actItem.merchantId + orFileName + "02";
            String chkValue = DigestMD5.MD5Sign(actItem.merchantId, tmpPalin.getBytes(getCharset("GBK", "batpay")), actItem.ownKeyStorePath);
            NameValuePair[] param = {
                    new NameValuePair("merId", actItem.merchantId),
                    new NameValuePair("fileName", orFileName),
                    new NameValuePair("queryType", "02"),
                    new NameValuePair("chkValue", chkValue)
            };
            String reqStr = "merId=" + actItem.merchantId + "&fileName=" + orFileName + "&queryType=02&chkValue=" + chkValue;
            WriteBankLogLn2("批量代付文件状态查询请求参数：\r\n" + reqStr);
            String result = sendBatch(param, bankFront.getUrl("queryfile"), "batpay");
            Map<String, String> resultMap = convertToMap(result);
            String stat = resultMap.get("stat");
            if (stat != null) {
                retAts.respCode = "0";
                retAts.transState = stat;
                retAts.payInfoCode = stat;
                if ("20IO".equals(stat)) {
                    String fileName = actItem.merchantId + "_" + tmpPaySendDate + "_" + tmpSeqNoContent + "_H.txt";
                    WriteBankLogLn2("要下载的文件名：" + fileName);
                    String signMsg = actItem.merchantId + orFileName + fileName;
                    String chkValue2 = DigestMD5.MD5Sign(actItem.merchantId, signMsg.getBytes(getCharset("GBK", "batpay")), actItem.ownKeyStorePath);
                    NameValuePair[] params = {
                            new NameValuePair("merId", actItem.merchantId),
                            new NameValuePair("orFileName", orFileName),
                            new NameValuePair("fileName", fileName),
                            new NameValuePair("chkValue", chkValue2)
                    };
                    String reqStr2 = "merId=" + actItem.merchantId + "&orFileName=" + orFileName + "&fileName=" + fileName + "&chkValue=" + chkValue2;
                    WriteBankLogLn2("批量代付回盘文件下载请求参数：" + reqStr2);
                    String results = sendBatch(params, bankFront.getUrl("querybatch"), "batpay");
                    // 拆分页面应答数据
                    int dex = results.lastIndexOf("=");
                    String ChkValue = results.substring(dex + 1);
                    String plainData = "";
                    String str[] = results.split("&");
                    if (str.length == 5) {
                        // 回盘文件下载成功
                        int Res_fileData = str[3].indexOf("=");
                        String FileData = str[3].substring(Res_fileData + 1);
                        String resultText = new String(MsgUtil.decodeInflate(FileData.getBytes()), getCharset("GBK", "batpay"));
                        plainData = resultText;
                        WriteBankLogLn("回盘文件内容:\r\n" + resultText);
                        boolean res = DigestMD5.MD5Verify(plainData.getBytes(getCharset("GBK", "batpay")), ChkValue, actItem.oppCertFilePath);
                        WriteBankLogLn("验签数据:" + res);
                        retAts.respCode = "0";
                        retAts.reqSeqID = p_req1998.reqBatchNO;
                        StringReader strReader = new StringReader(plainData);
                        BufferedReader tmpReader = new BufferedReader(strReader);
                        tmpReader.readLine();
                        while (true) {
                            String eachline = tmpReader.readLine();
                            if (StringHelper.isNullOrEmpty(eachline)) {
                                break;
                            }
                            if (eachline.indexOf("|") > 0) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                String[] detailNodes = eachline.split("\\|");
                                tmpRetDetail.recAct = detailNodes[4];
                                tmpRetDetail.recName = detailNodes[5];
                                tmpRetDetail.result = detailNodes[8];
                                tmpRetDetail.postScript = detailNodes[3];
                                tmpRetDetail.payAmount = amountDivide100(detailNodes[7]);
                                if (detailNodes.length > 10) {
                                    int i = checkString(detailNodes[10]);
                                    if (i == 0) {
                                        tmpRetDetail.payInfoCode = detailNodes[10];
                                        tmpRetDetail.memo = detailNodes[10];
                                    } else {
                                        tmpRetDetail.payInfoCode = detailNodes[10].substring(0, i);
                                        tmpRetDetail.memo = detailNodes[10].substring(0, i);
                                    }

                                }
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "没有查到回盘文件!";
                    }
                } else if ("20ED".equals(stat)) {
                    retAts.respInfo = "文件校验失败，整批失败!";
                } else if ("2094".equals(stat)) {
                    retAts.respInfo = "订单号重复，整批失败!";
                } else if ("20E9".equals(stat)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "IP地址不允许或商户号不存在";
                } else if ("2030".equals(stat)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "参数校验失败";
                } else if ("20FL".equals(stat)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "验证签名失败";
                } else {
                    retAts.respInfo = "交易处理中，请稍后查询!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "银行返回报文‘stat’字段为空!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        retAts.reqSeqID = p_req9188.reqBatchNO;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9188.ownAct, "batrec");
            if (actItem == null) {
                retAts.respCode = "0";
                retAts.respInfo = "未找到账号" + p_req9188.ownAct + "的批量商户配置节点";
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }

            // 批量代扣请求文件内容
            StringBuilder sbFileContent = new StringBuilder();
            // 批次号映射文件内容，以资金批次号命名映射文件，文件内容为发送银行的批次号（6位）
            StringBuilder batNoMappingContent = new StringBuilder();

            String tmpLocalMarkPath = getTempFileDirectory(p_req9188.getPayDateTime()) + File.separator + "batrec";
            String merchantId = actItem.merchantId;
            String tmpBatSeqNo = getBatSeqNo(tmpLocalMarkPath, 6);
            String totalNum = p_req9188.totalNum;
            String totalAmt = StringHelper.amountMultiply100(p_req9188.totalAmt);

            String tmpReqHeader = MessageFormat.format("{0}|{1}|{2}|{3}", merchantId, tmpBatSeqNo, totalNum, totalAmt);
            sbFileContent.append(tmpReqHeader).append("\r\n");
            batNoMappingContent.append(tmpBatSeqNo);

            String date = Format.Date8Format.format(p_req9188.getPayDateTime());
            while (p_req9188.readRecord()) {
                String orderNumber = p_req9188.readedDetail.askNumber;

                String cardType = "";//卡折标志 (0:卡,1:折)
                if ("1".equals(p_req9188.readedDetail.cardType)) {
                    cardType = "1";
                } else {
                    cardType = "0";
                }
                String payAct = p_req9188.readedDetail.payAct;
                String payName = p_req9188.readedDetail.payName;
                String certType = convertCertTypeToBank(p_req9188.readedDetail.certType);
                String certNum = p_req9188.readedDetail.certNum;
                String amount = StringHelper.amountMultiply100(p_req9188.readedDetail.payAmount);
                String usage = p_req9188.readedDetail.useType;
                String memo = orderNumber;

                //商户日期|交易类型|商户订单号|支付机构号|卡折标志|账号|账户名|证件类型|证件号|金额|用途|私有域|分账类型|分账方式|分账信息|渠道类型|交易模式|用户 ID|用户注册时间|用户注册邮箱|用户注册手机号|PC 硬盘序列号|PC mac 地址|手机串号 IMEI|用户 IP|代付经纬度信息|手机所在基站序列号|短信验证码输入操作特征|预留手机号|购买商品明细
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}||{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}||||{11}|{12}|||||||||||||", date, "0101", orderNumber, cardType, payAct, payName, certType, certNum, amount, usage, memo, "07", "1");
                sbFileContent.append(tmpReqBodyDetail).append("\r\n");
            }
            String tmpFileContent = sbFileContent.toString();
            WriteBankLogLn2("批次请求文件内容:\r\n" + tmpFileContent);

            //批次号映射文件处理
            String tmpUploadFileName = p_req9188.reqBatchNO + ".txt";
            String tmpUploadFilePath = tmpLocalMarkPath + File.separator + tmpUploadFileName;
            String tmpBatNoMappingContent = batNoMappingContent.toString();
            WriteBankLogLn2("批次号映射文件保存本地路径: " + tmpUploadFilePath);
            WriteBankLogLn2("批次号映射文件内容: " + tmpBatNoMappingContent);
            FileHelper.writeFile(tmpUploadFilePath, tmpBatNoMappingContent, getCharset("UTF-8", "batrec"));

            //批量代扣请求文件名
            String tmpFileName = merchantId + "_" + date + "_" + tmpBatSeqNo + "_" + "Q.txt";

            //批量代扣文件加密
            SecssUtil secssUtil = getSecssUtil(actItem);
            String fileContent = secssUtil.encodeEnvelope(tmpFileContent.getBytes(getCharset("UTF-8", "batrec")));

            Map<String, String> tmpBatRecRequest = new HashMap<String, String>();
            tmpBatRecRequest.put("Version", "20140728");
            tmpBatRecRequest.put("AccessType", "0");
            tmpBatRecRequest.put("InstuId", "");
            tmpBatRecRequest.put("AcqCode", "");
            tmpBatRecRequest.put("MerId", actItem.merchantId);
            tmpBatRecRequest.put("BusiType", "0001");
            tmpBatRecRequest.put("FileName", tmpFileName);
            tmpBatRecRequest.put("FileContent", fileContent);
            tmpBatRecRequest.put("BatchBgUrl ", actItem.notifyURL);
            tmpBatRecRequest.put("BatchResv", "");

            JSONObject transReserveJson = new JSONObject();
            transReserveJson.put("TerminalType", "08");
            transReserveJson.put("AcctInTp", "");
            transReserveJson.put("BizType", "");
            transReserveJson.put("SubTransType", "99100001");
            transReserveJson.put("MiniPayUrl", "");
            transReserveJson.put("MiniPayFlag", "");
            transReserveJson.put("DeviceMerId", "");
            tmpBatRecRequest.put("TranReserved", transReserveJson.toString());
            tmpBatRecRequest.put("Signature", "");


            Map<String, String> sendMap = new TreeMap<String, String>();
            Iterator<String> iterator = tmpBatRecRequest.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = tmpBatRecRequest.get(key);

                if (key.startsWith("__")) {
                    continue;
                }
                // 过滤空字段
                if (StringHelper.isNullOrEmpty(value)) {
                    continue;
                }
                sendMap.put(key, value);
            }

            WriteBankLogLn2("批量代扣提交请求数据:\r\n" + SDKUtil.coverMap2String(sendMap));

            secssUtil.sign(sendMap);

            if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
                sendMap.put("Signature", secssUtil.getSign());
                Map<String, String> tmpMapRet = sendDataToBank(sendMap, bankFront.getUrl("batrec"));
                if (tmpMapRet.size() > 0) {
                    retAts.respCode = "0";
                    retAts.respInfo = tmpMapRet.get("respMsg");
                    retAts.transState = tmpMapRet.get("respCode");
                    retAts.payInfoCode = tmpMapRet.get("respCode");
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银行响应数据为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "签名失败:" + secssUtil.getErrMsg();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
        retAts.reqSeqID = p_req9198.reqBatchNO;
        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req9198.ownAct, "batrec");
            if (actItem != null) {
                String merchantId = actItem.merchantId;

                // 读取接收资金报文中的批次号对应的发送银行的批次号
                String tmpBatNoMappingPath = getTempFileDirectory(p_req9198.getBgnDateTime()) + File.separator + "batrec" + File.separator + p_req9198.reqBatchNO + ".txt";
                WriteBankLogLn2("批次号映射文件保存本地路径:" + tmpBatNoMappingPath);
                if (!new File(tmpBatNoMappingPath).exists()) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次号映射文件不存在!";
                    return retAts;
                }
                String batchNo = FileHelper.readFileText(tmpBatNoMappingPath, getCharset("UTF-8", "batrec"));
                WriteBankLogLn2("本地批量代扣批次号映射文件内容:\r\n" + batchNo);

                String date = Format.Date8Format.format(p_req9198.getBgnDateTime());

                Map<String, String> tmpQryRequest = new HashMap<String, String>();
                tmpQryRequest.put("Version", "20140728");
                tmpQryRequest.put("AccessType", "0");
                tmpQryRequest.put("InstuId", "");
                tmpQryRequest.put("MerId", merchantId);
                tmpQryRequest.put("MerBatchId", batchNo);
                tmpQryRequest.put("MerBatchDate", date);
                tmpQryRequest.put("TranType", "0506");
                tmpQryRequest.put("BusiType", "0001");
                tmpQryRequest.put("MerResv", "");
                tmpQryRequest.put("Signature", "");

                Map<String, String> sendMap = new TreeMap<String, String>();
                Iterator<String> iterator = tmpQryRequest.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = tmpQryRequest.get(key);

                    if (key.startsWith("__")) {
                        continue;
                    }
                    // 过滤空字段
                    if (StringHelper.isNullOrEmpty(value)) {
                        continue;
                    }
                    sendMap.put(key, value);
                }

                WriteBankLogLn2("批量交易文件查询请求数据:\r\n" + SDKUtil.coverMap2String(sendMap));
                SecssUtil secssUtil = getSecssUtil(actItem);
                secssUtil.sign(sendMap);

                if (SecssConstants.SUCCESS.equals(secssUtil.getErrCode())) {
                    tmpQryRequest.put("Signature", secssUtil.getSign());

                    Map<String, String> tmpMapRet = sendDataToBank(tmpQryRequest, bankFront.getUrl("qrybatrec"));
                    WriteBankLogLn2("批量交易文件查询银行响应数据:\r\n" + SDKUtil.coverMap2String(tmpMapRet));
                    if (tmpMapRet.size() > 0) {
                        String tmpRespCode = tmpMapRet.get("respCode");
                        String tmpRespMsg = tmpMapRet.get("respMsg");
                        if ("0000".equals(tmpRespCode)) {
                            String orderStatus = tmpMapRet.get("OrderStatus");
                            if ("0000".equals(orderStatus)) {
                                String downloadFileName = tmpMapRet.get("DownloadFileName");
                                String oriFileName = merchantId + "_" + date + "_" + batchNo + "_" + "Q.txt";// 批量交易文件名称

                                Map<String, String> tmpQryRequest2 = new HashMap<String, String>();
                                tmpQryRequest2.put("Version", "20140728");
                                tmpQryRequest2.put("AccessType", "0");
                                tmpQryRequest2.put("InstuId", "");
                                tmpQryRequest2.put("MerId", merchantId);
                                tmpQryRequest2.put("OriFileName", oriFileName);
                                tmpQryRequest2.put("DownloadFileName", downloadFileName);
                                tmpQryRequest2.put("Signature", "");

                                Map<String, String> sendMap2 = new TreeMap<String, String>();
                                Iterator<String> iterator2 = tmpQryRequest2.keySet().iterator();
                                while (iterator2.hasNext()) {
                                    String key = iterator2.next();
                                    String value = tmpQryRequest2.get(key);

                                    if (key.startsWith("__")) {
                                        continue;
                                    }
                                    // 过滤空字段
                                    if (StringHelper.isNullOrEmpty(value)) {
                                        continue;
                                    }
                                    sendMap2.put(key, value);
                                }

                                WriteBankLogLn2("批量交易回盘文件内容下载请求数据:\r\n" + SDKUtil.coverMap2String(sendMap2));
                                SecssUtil secssUtil2 = getSecssUtil(actItem);
                                secssUtil2.sign(sendMap2);

                                if (SecssConstants.SUCCESS.equals(secssUtil2.getErrCode())) {
                                    tmpQryRequest2.put("Signature", secssUtil2.getSign());

                                    Map<String, String> tmpRetMap = sendDataToBank(tmpQryRequest2, bankFront.getUrl("qryfiledata"));
                                    WriteBankLogLn2("批量交易回盘文件内容下载银行响应数据:\r\n" + SDKUtil.coverMap2String(tmpRetMap));
                                    if (tmpRetMap.size() > 0) {
                                        String respCode = tmpRetMap.get("respCode");
                                        String respMsg = tmpRetMap.get("respMsg");
                                        if ("0000".equals(respCode)) {
                                            String tmpFileData = tmpRetMap.get("FileData");
                                            String fileData = new String(secssUtil2.decodeEnvelope(tmpFileData), getCharset("UTF-8", "batrec"));
                                            WriteBankLogLn2("批量交易回盘文件内容:\r\n" + fileData);
                                            StringReader strReader = new StringReader(fileData);
                                            BufferedReader tmpReader = new BufferedReader(strReader);
                                            while (true) {
                                                String eachline = tmpReader.readLine();
                                                if (StringHelper.isNullOrEmpty(eachline)) {
                                                    break;
                                                }
                                                if (eachline.indexOf("|") > 0) {
                                                    RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                                    String[] detailNodes = eachline.split("\\|");
                                                    if (detailNodes.length > 4) { // 文件尾（4个字段）：总笔数|总金额|成功笔数|成功金额
                                                        tmpRetDetail.payAct = detailNodes[7];
                                                        tmpRetDetail.payName = detailNodes[8];
                                                        tmpRetDetail.postScript = detailNodes[3];
                                                        tmpRetDetail.payAmount = amountDivide100(detailNodes[13]);
                                                        tmpRetDetail.result = detailNodes[4];
                                                        tmpRetDetail.payInfoCode = detailNodes[4];
                                                        retAts.writeRetDetail(tmpRetDetail);
                                                    } else {
                                                        break; // 若为文件尾，则不解析
                                                    }
                                                }
                                            }
                                        } else {
                                            retAts.respCode = "-1";
                                            retAts.respInfo = respMsg;
                                        }
                                    } else {
                                        retAts.respCode = "-1";
                                        retAts.respInfo = "批量交易回盘文件内容下载，银行响应数据为空!";
                                    }
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "签名失败:" + secssUtil2.getErrMsg();
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = "银行回盘文件未生成，请稍后查询！";
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpRespMsg;
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "批量交易文件查询，银行响应数据为空!";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "签名失败:" + secssUtil.getErrMsg();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req9198.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    public static int checkString(String str) {
        int res = 0;
        if (str != null) {
            for (int i = 0; i < str.length(); i++) {
                //只要字符串中有中文则为中文
                if (checkChar(str.charAt(i))) {
                    res = i;
                    break;
                }
            }
        }
        return res;
    }

    public static boolean checkChar(char ch) {
        if ((ch + "").getBytes().length == 1) {
            return true;//英文
        } else {
            return false;//中文
        }
    }
}
